var $newAddressBtn;
var $addressList;
var user;

function init() {

    $newAddressBtn = $('#newAddressBtn');
    $addressList = $('#addressList');
    user = JSON.parse($.cookie("user"));


}

function initView() {
    if (!user) {
        return;
    }
    var url = $.constant.webRoot() + 'v1/address?userId=' + user.id;
    var addressList = [];
    mui.ajax(url, {
        dataType: 'json',
        type: 'GET',
        async: false,
        success: function (data) {
            addressList = data;
        }
    });

    if (addressList.length !== 0) {
        for (var i = 0; i < addressList.length; i++) {
            var value = addressList[i];
            var $liHtml = $('<li class="mui-table-view-cell" data-id="' + value.id + '"></li>');
            var $delHtml = $('<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red">删除</a></div>');
            var $itemHtml = $('<div class="item mui-slider-handle"></div>');
            var $itemTitle = $('<div class="title-icon">' + value.receiveName.substr(0, 1) + '</div>');
            var $itemContent = $('<div class="content">' +
                '<div><span>' + value.receiveName + '</span><span class="receive-phone">' + value.receivePhone + '</span>' +
                (value.isDefault === '1' ? '<span class="receive-default">默認</span>' : '') +
                '</div><div>' + value.receiveAddress + '</div>' +
                '</div>');
            var $itemEdit = $('<div class="receive-edit">編輯</div>');

            $itemHtml.append($itemTitle);
            $itemHtml.append($itemContent);
            $itemHtml.append($itemEdit);
            $liHtml.append($delHtml);
            $liHtml.append($itemHtml);

            $addressList.append($liHtml);
        }

        $addressList.on('tap', '.mui-btn', function (event) {
            var li = this.parentNode.parentNode;
            mui.confirm('確定刪除該地址？', '地址', ['確認', '取消'], function (e) {
                if (e.index === 0) {
                    li.parentNode.removeChild(li);
                    var id = $(li).data("id");
                    mui.ajax($.constant.webRoot() + 'v1/address/' + id, {
                        dataType: 'json',
                        type: 'DELETE',
                        success: function (data) {
                        }
                    });
                } else {
                    setTimeout(function () {
                        mui.swipeoutClose(li);
                    }, 0);
                }
            });
        });

        $('.receive-edit').bind('tap', function () {
            var parentLi = $(this).parents("li");
            var id = parentLi.data("id");
            mui.openWindow('../newaddress/index.html?id=' + id, 'id');
        })
    }

    $newAddressBtn.bind('tap', function () {
        mui.openWindow('../newaddress/index.html', 'id');
    });

}


$(function () {
    init();
    initView();
});